<template>
  <div class="role-manage">
    <div class="query-form">
      <el-form :inline="true" :model="queryForm" ref="form">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <div>
          <el-button type="primary" size="mini" @click="handleAdd(1)">创建</el-button>
        </div>
        <el-table 
          :data="roleList" 
          style="width: 100%"
          row-key="_id"
        >
          <el-table-column  type="selection" width="55" />
          <el-table-column 
            v-for="item in columns" 
            :key="item.prop" 
            :label="item.label" 
            :prop="item.prop" 
            width="180" 
            :formatter="item.formatter"
          />
          <el-table-column label="操作" width="240">
            <template #default="scope">
              <el-button type="primary" size="mini" @click="handlerPermission(scope.row)">设置权限</el-button>
              <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row._id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          background 
          layout="prev, pager, next" 
          :total="pager.total" 
          class="pagination" 
          @current-change="handleCurrentChange"
          />
      </div>
    </div>
    <el-dialog
      title="角色新增"
      v-model="showModal"
      :before-close="handleClose"
    >
      <el-form
        :model="roleForm"
        label-width="120px"
        ref="dialogForm"
        :rules="rules"
      >
        <el-form-item prop="roleName" label="角色名称">
          <el-input placeholder="请输入角色名称" v-model="roleForm.roleName" />
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input type="text-area" :row="2" placeholder="请输入备注" v-model="roleForm.remark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      title="设置权限"
      v-model="showPermissionModal"
      :before-close="handlePermissionClose"
    >
      <el-form
        label-width="120px"
      >
        <el-form-item prop="roleName" label="角色名称">
          {{ curRoleName }}
        </el-form-item>
        <el-form-item prop="remark" label="选择权限">
          <el-tree 
            ref="PermissionRef"
            :data="menuList" 
            show-checkbox
            node-key="_id"
            :props="{label: 'menuName'}"
            default-expand-all
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showPermissionModal = false">取消</el-button>
          <el-button type="primary" @click="handlerPermissionSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import utils from "../utils/utils";

export default {
  name: 'Menu',
  data() {
    return {
      queryForm: {
        roleName: ''
      },
      roleList: [],
      columns: [
        {
          label: '角色名称',
          prop: 'roleName'
        },
        {
          label: '备注',
          prop: 'remark'
        },
        {
          label: '权限列表',
          prop: 'permissionList',
          formatter: (row,column,value) => {
            let names = []
            let list = value.halfCheckedKeys || []
            list.map((key) => {
              let name = this.actionMap[key];
              if (key && name) names.push(name);
            })
            return names.join(',')
          }
        },
        {
          label: '创建时间',
          prop: 'createTime',
          formatter(row, column, cellValue) {
            return utils.formateDate(new Date(cellValue))
          }
        }
      ],
      pager: {
        total: 1,
        pageSize: 10
      },
      roleForm: {
      },
      showModal: false,
      action: 'create',
      rules: {
        roleName:[
          {
            required: true,
            message: '请输入角色的名称',
            trigger: 'blur'
          }
        ]
      },
      showPermissionModal: false,
      curRoleName: '',
      curRoleId: '',
      menuList: [],
      actionMap: {}
    }
  },
  mounted() {
    this.getRoleList()
    this.getMenuList()
  },
  methods: {
    async getRoleList() {
      const { list, page } = await this.$api.roleList({
        ...this.pager,
        ...this.queryForm
      })
      this.roleList = list
      this.pager.total = page.total
    },
    handleCurrentChange(current) {
      this.pager.pageNum = current
      this.getRoleList()
    },
    handleQuery() {
      this.getRoleList()
    },
    handleReset(form) {
      this.$refs[form].resetFields()
    },
    handleAdd() {
      this.showModal = true
      this.action = 'create'
    },
    handleEdit(row) {
      this.showModal = true
      this.action = 'edit'
      this.$nextTick(() => {
        Object.assign(this.roleForm, row)
      })
    },
    async handleDelete(id) {
      await this.$api.roleSubmit({_id: id, action: 'delete'})
      this.$message.success('删除成功')
      this.getRoleList()
    },
    handleClose() {
      this.handleReset('dialogForm')
      this.showModal = false
    },
    handleSubmit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if(valid) {
          let { action, roleForm } = this
          const params = { ...roleForm, action }
          const res = await this.$api.roleSubmit(params)
          if(res) {
            this.$message.success('操作成功')
            this.showModal = false
            this.handleReset('dialogForm')
            this.getRoleList()
          }
        }
      })
    },
    handlePermissionClose() {
      this.showPermissionModal = false
    },
    handlerPermission(row) {
      this.showPermissionModal = true
      this.curRoleId = row._id
      this.curRoleName = row.roleName
      const { checkedKeys } = row.permissionList
      setTimeout(() => {
        this.$refs.PermissionRef.setCheckedKeys(checkedKeys)
      })
    },
    async getMenuList() {
      const list = await this.$api.menuList()
      this.menuList = list
      this.getActionMap(list);
    },
    async handlerPermissionSubmit() {
      let nodes = this.$refs.PermissionRef.getCheckedNodes()
      let halfKeys = this.$refs.PermissionRef.getHalfCheckedKeys()
      let checkedKeys = []
      let parentKeys = []
      nodes.map((node) => {
        if(!node.children) {
          checkedKeys.push(node._id)
        } else {
          parentKeys.push(node._id)
        }
      })
      let params = {
        _id: this.curRoleId,
        permissionList: {
          checkedKeys,
          halfCheckedKeys: parentKeys.concat(halfKeys)
        }
      }
      await this.$api.updatePermission(params)
      this.showPermissionModal = false
      this.$message.success('设置成功')
      this.getRoleList()
    },
    getActionMap(list) {
      let actionMap = {}
      const deep = (arr) => {
        while(arr.length) {
          let item = arr.pop()
          if(item.children) {
            actionMap[item._id] = item.menuName
          }
          if(item.children && !item.action) {
            deep(item.children)
          }
        }
      }
      deep(JSON.parse(JSON.stringify(list)));
      this.actionMap = actionMap
    }
  }
}
</script>

<style scoped>

</style>